#!/bin/sh
. /usr/share/os-prober/common.sh
set -e

partition="$1"
bootpart="$2"
mpoint="$3"
type="$4"

found_item=0

dequote () {
	item="${1%\"}"
	echo "${item#\"}"
}

recordstanza () {
	if [ -n "$kernel" ]; then
		# TODO: handle device=/partition= to find images
		if ! [ -e "$mpoint/$kernel" ]; then
			debug "cannot find $kernel; not recording"
			return
		fi
		if [ "$initrd" ] && ! [ -e "$mpoint/$initrd" ]; then
			debug "cannot find $initrd: not recording"
			return
		fi

		if [ -z "$title" ]; then
			title="${kernel##*/}"
		fi
		if [ "$read_only" ]; then
			parameters="ro $parameters"
		fi
		if [ "$rootdev" ]; then
			parameters="root=$rootdev $parameters"
		fi
		parameters="${parameters% }"
		result "$rootpart:$bootpart:$title:$kernel:$initrd:$parameters"
		found_item=1

		title=
		rootdev="$default_rootdev"
		kernel="$default_kernel"
		parameters="$default_parameters"
		initrd="$default_initrd"
		read_only="$default_read_only"
	else
		# Everything in the global options section set default values.
		default_rootdev="$rootdev"
		default_kernel="$kernel"
		default_parameters="$parameters"
		default_initrd="$initrd"
		default_read_only="$read_only"
	fi
}

parse_yaboot_conf () {
	mpoint="$1"
	rootpart="$2"
	bootpart="$3"
	IFS=" 	="
	while read line; do
		debug "parsing: $line"
		set -f
		set -- $line
		set +f
		case "$1" in
			root)
				rootdev="$(dequote "$2")"
			;;
			image)
				recordstanza
				kernel="$(dequote "$2")"
			;;
			append)
				cleanappend=`printf %s "$line" | sed 's/append\([[:space:]]\)*=\([[:space:]]\)*//'`
				parameters="$(dequote "$cleanappend")"
			;;
			initrd)
				initrd="$(dequote "$2")"
			;;
			label)
				shift 1
				title="$(dequote "$*")"
			;;
			alias)
				shift 1
				titlealias="$(dequote "$*")"
			;;
			read-only)
				read_only=1
			;;
		esac
	done
	recordstanza
}

# Avoid failing if archdetect is missing (running outside d-i). This is
# suboptimal but will do for now.
if type archdetect >/dev/null 2>&1; then
	case "`archdetect`" in
		powerpc/powermac_newworld)
		;;
		powerpc/chrp*)
		;;
		*)
			exit 1
		;;
	esac
fi

if [ -e "$mpoint/etc/yaboot.conf" ]; then
	debug "parsing yaboot.conf"
	parse_yaboot_conf "$mpoint" "$partition" "$bootpart" < "$mpoint/etc/yaboot.conf"
fi

if [ "$found_item" = 0 ]; then
	exit 1
else
	exit 0
fi
